import 'dart:async';

import 'package:flutter/material.dart';
import 'package:silver_flutter/event/user_events.dart';
import 'package:silver_flutter/event_bus.dart';
import 'package:silver_flutter/model/user.dart';
import 'package:silver_flutter/widget/authed.dart';
import 'package:silver_flutter/api.dart' as api;

class UserPage extends StatefulWidget {
  UserPage({Key key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return new _UserPageState();
  }
}

class _UserPageState extends State<UserPage> {
  StreamSubscription _loginSub;
  StreamSubscription _logoutSub;

  bool _isLoggedIn = api.isLoggedIn();

  @override
  void dispose() {
    _loginSub.cancel();
    _logoutSub.cancel();

    super.dispose();
  }

  @override
  void initState() {
    super.initState();

    _loginSub = eventBus.on(UserLoggedInEvent).listen((event) {
      setState(() {
        _isLoggedIn = true;
      });
    });

    _logoutSub = eventBus.on(UserLoggedOutEvent).listen((event) {
      setState(() {
        _isLoggedIn = false;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
        title: Text('我的'),
        actions: _isLoggedIn
            ? <Widget>[
                FlatButton(
                  child: Text('退出'),
                  textColor: Colors.white,
                  onPressed: () {
                    api.logout();
                  },
                )
              ]
            : [],
      ),
      body: new Authed(
        builder: (context) => new FutureBuilder<User>(
              future: api.fetchUser(),
              builder: (context, snapshot) {
                return Center(
                  child: Row(
                    children: snapshot.hasData
                        ? <Widget>[
                            Container(
                              width: 48.0,
                              height: 48.0,
                              padding: EdgeInsets.all(4.0),
                              child: Image.network(snapshot.data.avatarUrl),
                            ),
                            Text(snapshot.data.displayName),
                          ]
                        : [],
                    mainAxisAlignment: MainAxisAlignment.center,
                  ),
                );
              },
            ),
      ),
    );
  }
}
